import 'dart:io';

import 'package:flutter/material.dart';
import 'package:happy_elf_app/apis/user.dart';
import 'package:happy_elf_app/utils/color.dart';
import 'package:happy_elf_app/views/Home/split/breakDown.dart';
import 'package:happy_elf_app/views/Home/split/enter.dart';
import 'package:happy_elf_app/views/Home/split/generate.dart';
import 'package:happy_elf_app/widgets/headerBack/index.dart';
import 'package:speech_to_text/speech_to_text.dart' as stt;
import 'package:audioplayers/audioplayers.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:record/record.dart';
import 'package:path_provider/path_provider.dart';

class SplitDefalut extends StatefulWidget {
  const SplitDefalut({
    Key? key,
    this.callback,
  }) : super(key: key);

  final Function? callback;

  @override
  State<SplitDefalut> createState() => _SplitDefalutState();
}

class _SplitDefalutState extends State<SplitDefalut>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  bool isEntering = false; // 正在输入
  // 录音相关
  final AudioRecorder _audioRecorder = AudioRecorder();
  bool _isRecording = false;
  String? _audioPath;
  String? _currentRecordingModule; // 记录当前正在录音的模块

  // 播放相关
  final AudioPlayer _audioPlayer = AudioPlayer();
  bool _isPlaying = false;

  // 语音转文字相关
  late stt.SpeechToText _speech;
  bool _speechAvailable = false;

  // 模块状态 - 记录每个模块的录制状态
  final Map<String, bool> _moduleRecordedStatus = {
    'envCondition': false,
    'action': false,
    'consequence': false,
  };
  String _tempRecognizedText = ''; // 临时识别结果

  // 页面状态 0语音输入 1摇一摇 2拆分 3生成
  int page = 0;
  int taskId = 0; // 任务id
  String targetId = ''; // 目标id
  Map enterTimes = {};
  int durationSec = 0; // 秒数

  // 存储每个模块的录音路径
  final Map<String, String?> _moduleAudioPaths = {
    'envCondition': null,
    'action': null,
    'consequence': null,
  };

  // 初始化权限和语音识别
  Future<void> _initPermissionAndSpeech() async {
    bool hasAllPermissions = await _checkAllPermissions();
    if (!hasAllPermissions) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('麦克风和语音识别权限均需开启')),
        );
      }
      return;
    }
    await _initSpeech();
  }

  // 页面进入
  void enter(String pageName) {
    durationSec = DateTime.now().millisecondsSinceEpoch;
    _sendEvent(pageName, "enter");
  }

  // 页面离开
  void leave(String pageName) {
    if (durationSec != 0) {
      final time =
          ((DateTime.now().millisecondsSinceEpoch - durationSec)).round();
      _sendEvent(pageName, "leave", time: time);
    }
  }

  Future<void> _sendEvent(String pageName, String type, {int? time}) async {
    Map data = {
      "pageName": pageName,
      "eventType": type,
      if (time != null) "duration": time
    };
    var res = await User().report(data);
    print('上报时间$res');
    if (res['code'] == 200) {}
  }

  // 检查所有权限
  Future<bool> _checkAllPermissions() async {
    Map<Permission, PermissionStatus> statuses = await [
      Permission.microphone,
      Permission.speech,
    ].request();

    if (statuses[Permission.microphone] == PermissionStatus.permanentlyDenied) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请授予麦克风权限以使用语音功能')),
      );
      return false;
    }
    if (statuses[Permission.speech] == PermissionStatus.permanentlyDenied) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请授予语音识别权限以使用语音功能')),
      );
      return false;
    }

    return statuses[Permission.microphone]!.isGranted &&
        statuses[Permission.speech]!.isGranted;
  }

  // 检查麦克风权限
  Future<bool> _checkMicrophonePermission() async {
    var status = await Permission.microphone.status;
    if (status.isGranted) return true;

    status = await Permission.microphone.request();
    if (status.isGranted) return true;

    if (status.isPermanentlyDenied && mounted) {
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: const Text('需要麦克风权限'),
          content: const Text('请在设置中开启麦克风权限以使用录音功能'),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () => openAppSettings(),
              child: const Text('去设置'),
            ),
          ],
        ),
      );
    }
    return false;
  }

  // 初始化语音识别
  Future<void> _initSpeech() async {
    final available = await _speech.initialize(
      onStatus: (status) => debugPrint('语音识别状态: $status'),
      onError: (error) => debugPrint('语音识别错误: $error'),
    );
    setState(() => _speechAvailable = available);
  }

  // 开始录音
  Future<void> _startRecording(String module) async {
    if (_isRecording) return;
    _currentRecordingModule = module;

    final hasPermission = await _checkMicrophonePermission();
    if (!hasPermission) return;

    // 准备录音路径
    final appDir = await getApplicationDocumentsDirectory();
    final dirPath = '${appDir.path}/voice_records';
    await Directory(dirPath).create(recursive: true);
    final timestamp = DateTime.now().millisecondsSinceEpoch;
    final path = '$dirPath/${module}_$timestamp.wav';

    // 开始录音
    await _audioRecorder.start(const RecordConfig(), path: path);
    setState(() {
      _isRecording = true;
      _audioPath = path;
    });

    // 开始语音识别
    if (_speechAvailable) {
      _speech.listen(
        onResult: (result) => setState(() {
          _tempRecognizedText = result.recognizedWords;
          // 实时更新当前模块的识别文本
          _updateModuleText(module, _tempRecognizedText);
        }),
        localeId: 'zh_CN',
        partialResults: true,
        listenFor: const Duration(seconds: 30),
        pauseFor: const Duration(seconds: 3),
      );
    }
  }

  // 停止录音
  Future<void> _stopRecording() async {
    if (!_isRecording || _currentRecordingModule == null) return;

    await _audioRecorder.stop();
    // 更新模块状态为已录制
    setState(() {
      _isRecording = false;
      _moduleRecordedStatus[_currentRecordingModule!] = true;
      _moduleAudioPaths[_currentRecordingModule!] = _audioPath;
      // 保存最终识别结果
      _updateModuleText(_currentRecordingModule!, _tempRecognizedText);
      _tempRecognizedText = '';
    });
    _speech.stop();
    _currentRecordingModule = null;
  }

  // 更新模块文本
  void _updateModuleText(String module, String text) {
    setState(() {
      switch (module) {
        // case 'envCondition':
        //   environment = text.isNotEmpty ? text : '未识别';
        //   break;
        // case 'action':
        //   action = text.isNotEmpty ? text : '未识别';
        //   break;
        // case 'consequence':
        //   consequence = text.isNotEmpty ? text : '未识别';
        //   break;
      }
    });
  }

  // 播放录音
  Future<void> _playRecording(String? path) async {
    if (path == null || _isRecording || _isPlaying) return;

    setState(() => _isPlaying = true);
    try {
      await _audioPlayer.play(DeviceFileSource(path));
      _audioPlayer.onPlayerComplete.listen((_) {
        if (mounted) setState(() => _isPlaying = false);
      });
    } catch (e) {
      debugPrint('播放错误: $e');
      if (mounted) setState(() => _isPlaying = false);
    }
  }

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 1),
    );
    enter('任务拆分');
    _speech = stt.SpeechToText();
    _initPermissionAndSpeech();
  }

  @override
  void dispose() {
    _speech.stop();
    _controller.dispose();
    _audioPlayer.dispose();
    _audioRecorder.dispose();
    leave('任务拆分');
    super.dispose();
  }

  // 标题组件
  Widget textTitle({required String text, String? type = ''}) {
    return SizedBox(
      width: 152,
      child: Text(
        text,
        style: const TextStyle(
          color: Colors.black,
          fontSize: 20,
          fontFamily: 'Inter',
          fontWeight: FontWeight.w400,
          height: 1.25,
        ),
        textAlign: type == 'action' ? TextAlign.right : TextAlign.left,
      ),
    );
  }

  // 录音按钮组件 - 核心优化点
  Widget speechButton(String module) {
    // 按钮背景色逻辑：
    // 1. 正在录音时（当前模块）：红色
    // 2. 已录制完成：红色
    // 3. 未录制：白色
    bool isCurrentRecording = _isRecording && _currentRecordingModule == module;
    bool isRecorded = _moduleRecordedStatus[module] ?? false;
    bool shouldBeRed = isCurrentRecording || isRecorded;

    return Container(
      width: 126,
      height: 126,
      alignment: Alignment.center,
      padding: const EdgeInsets.symmetric(horizontal: 15.49),
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        color: shouldBeRed ? hexColor('E9614D') : Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.3),
            blurRadius: 4,
            offset: const Offset(0, 2),
          )
        ],
      ),
      child: Image.asset(
        shouldBeRed
            ? 'lib/assets/images/home/speech-after.png'
            : 'lib/assets/images/home/speech-before.png',
        width: 29.90,
        height: 28.91,
        fit: BoxFit.contain,
      ),
    );
  }

  // 构建单个语音模块
  Widget _buildVoiceModule({
    required String title,
    required String module,
  }) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        if (module != 'action') textTitle(text: title),
        GestureDetector(
          onTap: () => _playRecording(_moduleAudioPaths[module]),
          onLongPressStart: (_) => _startRecording(module),
          onLongPressEnd: (_) => _stopRecording(),
          // 长按取消时也停止录音
          onLongPressCancel: () => _stopRecording(),
          child: speechButton(module),
        ),
        if (module == 'action') textTitle(text: title, type: 'action'),
      ],
    );
  }

  // 提交到后端
  void _submitToBackend() {
    setState(() => page = 1);
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        children: [
          HeaderBack(
            title: page == 2
                ? '任务拆分'
                : page == 3
                    ? '生成精灵'
                    : '任务抽取',
            isFirst: page != 0,
            callback: () {
              if (page > 0) {
                setState(() => page--);
              }
            },
          ),
          page == 0
              ? Padding(
                  padding:
                      const EdgeInsets.symmetric(vertical: 36, horizontal: 24),
                  child: Column(
                    children: [
                      // 环境条件模块
                      _buildVoiceModule(
                        title: '描述实现目标的必要环境条件',
                        module: 'envCondition',
                      ),
                      const SizedBox(height: 52),
                      // 具体行动模块
                      _buildVoiceModule(
                        title: '描述实现目标的具体行动',
                        module: 'action',
                      ),
                      const SizedBox(height: 52),
                      // 行动后果模块
                      _buildVoiceModule(
                        title: '表明采取行动的后果',
                        module: 'consequence',
                      ),
                      const SizedBox(height: 40),
                      // 底部按钮
                      _isRecording
                          ? Image.asset(
                              'lib/assets/images/home/enter.png',
                              width: 280,
                              height: 65,
                            )
                          : Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                ElevatedButton(
                                  onPressed: () {
                                    setState(() {
                                      _moduleRecordedStatus.forEach((key, _) =>
                                          _moduleRecordedStatus[key] = false);
                                      _moduleAudioPaths.forEach((key, _) =>
                                          _moduleAudioPaths[key] = null);
                                    });
                                  },
                                  style: ElevatedButton.styleFrom(
                                      backgroundColor: Colors.grey),
                                  child: const Text('重新录制'),
                                ),
                                const SizedBox(width: 20),
                                ElevatedButton(
                                  style: ElevatedButton.styleFrom(
                                      backgroundColor: hexColor('#E9614D')),
                                  onPressed: _submitToBackend,
                                  child: const Text('      完成      '),
                                ),
                              ],
                            ),
                    ],
                  ),
                )
              : page == 1
                  ? Enter(callBack: (id) {
                      setState(() => page = 2);
                      taskId = id;
                    })
                  : page == 2
                      ? SingleChildScrollView(
                          child: breakDown(
                              taskId: taskId,
                              callBack: (id) {
                                targetId = id.toString();
                                page = 3;
                                setState(() {});
                              }),
                        )
                      : Generate(
                          targetId: targetId,
                          callBack: () {
                            // 去任务追踪
                            widget.callback!();
                          },
                        )
        ],
      ),
    );
  }
}
